package com.lalosoft.gastostarjetaweb.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lalosoft.gastostarjetaweb.Constants;
import com.lalosoft.gastostarjetaweb.dao.ItemDao;
import com.lalosoft.gastostarjetaweb.dao.UserDao;
import com.lalosoft.gastostarjetaweb.model.Item;
import com.lalosoft.gastostarjetaweb.model.User;
import com.lalosoft.gastostarjetaweb.pmf.PMF;
import com.lalosoft.gastostarjetaweb.util.EmailSender;

@SuppressWarnings("serial")
public class RecordarGastoServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger("RecordarGastoServlet");
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		log.log(Level.WARNING, "Recordatorio gastos inicia ");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<User> users = UserDao.findAll(pm);
		try {
			for(User user : users){
				List<Item> items = ItemDao.findByToken(user.getUuid(), pm);
				try {
					enviarEmail(user.getEmail(), items, pm);
					log.log(Level.WARNING, "Email enviado a : " + user.getEmail());
				} catch (MessagingException e) {
					log.log(Level.WARNING, "Error al enviar email: " + e.getMessage(), e);
				}
			}
		} finally {
			pm.close();
		}
	}
	
	private void enviarEmail(String email, List<Item> items, PersistenceManager pm) throws UnsupportedEncodingException, MessagingException{
		EmailSender sender = new EmailSender(Constants.ADDRESS, email);
		StringBuffer buffer = new StringBuffer();
		for(Item item : items){
			buffer.append(fillItem(item));
			buffer.append("\n");
			actualizarItem(item, pm);
		}
		sender.send("Gastos Tarjeta", buffer.toString());
	}
	
	private String fillItem(Item item){
		StringBuffer body = new StringBuffer();
		body.append("Item:" + "\n");
		body.append(item.getDetalle() + "\n");
		return body.toString();
	}
	
	private void actualizarItem(Item item, PersistenceManager pm){
		log.log(Level.WARNING, "Se va actualizar item: " + item.getDetalle());
		int cuotasRestantes = Integer.valueOf(item.getCuotasRestantes());
		cuotasRestantes--;
		if(cuotasRestantes == 0){
			ItemDao.deleteById(Long.valueOf(item.getId()), pm);
		} else {
			item.setCuotasRestantes(String.valueOf(cuotasRestantes));
			ItemDao.update(item, pm);
		}
	}
}
